package com.fengplus.demo.service.impl;

import com.fengplus.demo.entity.AppProduct;
import com.fengplus.demo.entity.AppProductStock;
import com.fengplus.demo.mapper.AppProductMapper;
import com.fengplus.demo.mapper.AppProductStockMapper;
import com.fengplus.demo.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private AppProductMapper productMapper;

    @Autowired
    private AppProductStockMapper productStockMapper;

    @Override
    public AppProduct findOne(Long id) {
        return productMapper.findOne(id);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public int save(AppProduct product, Integer amount) {
        int result;
        try {
            productMapper.save(product);
            productStockMapper.save(product.getId(), amount);
            result = 1;
        } catch (Exception e) {
            result = 0;
        }

        return result;
    }

    @Override
    public int findStock(Long productId) {
        AppProductStock productStock = productStockMapper.findOne(productId);
        int stock = productStock == null ? 0 : productStock.getAmount();
        return stock;
    }

    @Override
    public int decreaseStock(Long productId, Integer amount) {
        return productStockMapper.decrease(productId, amount);
    }

}
